//
//  MNDCanTransferViewController.m
//  minidai
//
//  Created by 谭谭伟 on 17/5/14.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDCanTransferViewController.h"
#import "MNDAllowTransferModel.h"
#import "SYRefreshControl.h"
#import "MNDCanTransferTableViewCell.h"
#import "MNDInvestmentDetailViewController.h"
#import "MNDConfirmTransferViewController.h"
@interface MNDCanTransferViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) NSMutableArray<MNDAllowTransferModel*> *allowTransferModelArray;
@property (assign, nonatomic) NSInteger pageNum;
@property (weak, nonatomic) IBOutlet UITableView *allowTransferTableView;

@end

@implementation MNDCanTransferViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    
}
#pragma mark -懒加载
- (NSMutableArray<MNDAllowTransferModel *> *)allowTransferModelArray {
    if (!_allowTransferModelArray) {
        _allowTransferModelArray = [[NSMutableArray alloc]init];
    }
    return _allowTransferModelArray;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadData:YES];

}
#pragma mark -加载数据
- (void)loadData:(BOOL)isPullDown {
    if (self.allowTransferModelArray.count <= 0) {
        [self.view beginLoading];
    }
    if (isPullDown) {
        if (self.allowTransferModelArray.count <= 0) {
            [self.view beginLoading];
        }
        _pageNum = 1;
    } else {
        _pageNum++;
    }
    __weak typeof(self) weakSelf = self;
    
    //转让中数据获取
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"perpage": @(_pageNum),@"pagesize": @5, @"creditor_status": @1}];
    
    [APIManager sendRequestWithPath:API_ALLOW_TENDER_TRANSFER_LIST parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
    
            NSArray *modelArray = [MNDAllowTransferModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"li"]];
            
            if (isPullDown) {
                [weakSelf.view configBlankPage:SYBlankPageTypeNoData hasData:modelArray.count reloadButtonBlock:nil];
                [weakSelf.allowTransferModelArray removeAllObjects];
            }
            [weakSelf.allowTransferModelArray addObjectsFromArray:modelArray];
            [SYRefreshControl configAfterLoading:weakSelf.allowTransferTableView hasData:modelArray.count];
        } else {
            [SYRefreshControl configAfterLoading:weakSelf.allowTransferTableView hasData:YES];
            if (isPullDown) {
                [weakSelf.view configBlankPage:SYBlankPageTypeError hasData:NO reloadButtonBlock:^(id sender) {
                    [weakSelf loadData:isPullDown];
                }];
            }
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        [weakSelf.allowTransferTableView reloadData];
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.allowTransferTableView hasData:YES];
        if (isPullDown) {
            SYBlankPageType blankType = [weakSelf.view blankPageTypeWithError:error];
            [weakSelf.view configBlankPage:blankType hasData:weakSelf.allowTransferModelArray.count reloadButtonBlock:^(id sender) {
                [weakSelf loadData:isPullDown];
            }];
        } else {
            [NetworkProgressHUD showHudNetworkError:error];
        }
    }];
}

#pragma mark -搭建界面
- (void)setupUI {
    WeakSelf(self);
    [SYRefreshControl configGifMJRefresh:self.allowTransferTableView refreshType:MJRefreshSupportALl beginRefresh:NO timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        [weakself loadData:YES];
    } loadMoreBlock:^{
        [weakself loadData:NO];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.allowTransferModelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MNDAllowTransferModel *model = self.allowTransferModelArray[indexPath.section];
    MNDCanTransferTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDCanTransferTableViewCell"];
    cell.borrowTitleLabel.text = model.borrow_title;
    cell.tenderMoneyLabel.text = model.tender_money;
    cell.borrowYearAprLabel.text = model.borrow_year_apr;
    cell.tenderAddTimeLabel.text = [NSString stringWithFormat:@"出借日期：%@",model.tender_add_time];
    cell.borrowDeadlineLabel.text = [NSString stringWithFormat:@"%@个月",model.borrow_deadline];
    cell.incomeMoneyLabel.text = model.expect_income;
    if (model.sum_apr.doubleValue > 0) {
        NSString *str = [NSString stringWithFormat:@"+%.1f",model.coupon_apr.floatValue*100];

        cell.couponAprLabel.text = [NSString stringWithFormat:@"%@%%",str];
        cell.couponAprLabel.hidden = NO;
        cell.iconImgView.hidden = NO;
    }else {
        cell.couponAprLabel.hidden = YES;
        cell.iconImgView.hidden = YES;
    }
        return cell;
}

//侧滑
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    //债权转让侧滑
    UITableViewRowAction *transferRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault  title:@"转让债权" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        //跳转到债权转让页面
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"TenderTransfer" bundle:[NSBundle mainBundle]];
        MNDConfirmTransferViewController *confirmVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDConfirmTransferViewController"];
        confirmVC.tenderId = self.allowTransferModelArray[indexPath.section].tender_id;
        confirmVC.yearApr = self.allowTransferModelArray[indexPath.section].borrow_year_apr;
        [self.navigationController pushViewController:confirmVC animated:YES];
                }];
    transferRowAction.backgroundColor = GlobalColor;
    return @[transferRowAction];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"InvestmentRecord" bundle:nil];
    MNDInvestmentDetailViewController *investmentDetailVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDInvestmentDetailViewController"];
    investmentDetailVC.tenderId = self.allowTransferModelArray[indexPath.section].tender_id;
    investmentDetailVC.allowTransfer = YES;
    investmentDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:investmentDetailVC animated:YES];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
